import javax.naming.*
import javax.jms.*

/** Obtain a connection factory from JNDI and create a JMS session, then pass
    to user closure. */
def withJmsSession(closure) {
	def ctx = new InitialContext()
	try {
		def cf = ctx.lookup("ConnectionFactory") as ConnectionFactory
		def conn = cf.createConnection()
		try {
			def session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE)
			conn.start()
			closure.call(session)
			session.close()
		} finally {
			conn.close()
		}
	} finally {
		ctx.close()
	}
}
//withJmsSession { session -> println(session) }
def sendMsgToQueue(session, msg, queueName) {
	println("Sending JMS msg to queue ${queueName}")
	def queue = session.createQueue(queueName)
	def producer = session.createProducer(queue)
	producer.send(msg)
}
def sendTextFileToQueue(session, textFile, queueName) {
	def textMsg = session.createTextMessage(textFile.text)
	textMsg.setStringProperty("filePath", textFile.path)
	sendMsgToQueue(session, textMsg, queueName)
	println("File sent: ${textFile}")
}

queueName = args[0]
text = args[1]
withJmsSession { session -> 
	def msg = session.createTextMessage(text)
	sendMsgToQueue(session, msg, queueName)
}